﻿using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;
using System.Collections.Generic;
using System.Linq;

namespace TodoApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class TodoController : ControllerBase
    {
        private static List<TodoItem> todos = new List<TodoItem>();
        private static int nextId = 1;

        // GET: api/todo
        [HttpGet]
        public ActionResult<IEnumerable<TodoItem>> GetAll()
        {
            return Ok(todos);
        }

        // GET: api/todo/1
        [HttpGet("{id}")]
        public ActionResult<TodoItem> GetById(int id)
        {
            var todo = todos.FirstOrDefault(t => t.Id == id);
            if (todo == null)
                return NotFound();
            return Ok(todo);
        }

        // POST: api/todo
        [HttpPost]
        public ActionResult<TodoItem> Create(TodoItem item)
        {
            item.Id = nextId++;
            todos.Add(item);
            return CreatedAtAction(nameof(GetById), new { id = item.Id }, item);
        }

        // PUT: api/todo/1
        [HttpPut("{id}")]
        public IActionResult Update(int id, TodoItem item)
        {
            var existing = todos.FirstOrDefault(t => t.Id == id);
            if (existing == null)
                return NotFound();

            existing.Title = item.Title;
            existing.IsCompleted = item.IsCompleted;
            return NoContent();
        }

        // DELETE: api/todo/1
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var item = todos.FirstOrDefault(t => t.Id == id);
            if (item == null)
                return NotFound();
            todos.Remove(item);
            return NoContent();
        }
    }
}
